#include "stm32f4xx.h"                  // Device header

void StandBy_In(void)
{
	RCC_AHB1PeriphResetCmd(0x01ff,ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);
	
	RTC_ClearFlag(RTC_FLAG_WUTF);
	RTC_WakeUpCmd(ENABLE); // Start WKUP for next awake
	
	PWR_EnterSTANDBYMode();
}

void MODE_GPIO_Init(){
	GPIO_InitTypeDef GPIO_InitStructure;

    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); // SYSCFG CLK Enable

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
	SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA,EXTI_PinSource0);
	
	EXTI_InitTypeDef EXTI_InitStruct;
	EXTI_InitStruct.EXTI_Line = EXTI_Line0;
	EXTI_InitStruct.EXTI_LineCmd = ENABLE;
	EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt;
	EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Rising;
	EXTI_Init(&EXTI_InitStruct);

	NVIC_InitTypeDef NVIC_InitStruct;
	NVIC_InitStruct.NVIC_IRQChannel = EXTI0_IRQn;
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStruct.NVIC_IRQChannelSubPriority = 3;
	NVIC_Init(&NVIC_InitStruct);
	
	if((GPIOA->IDR & 0x01)==0){
		StandBy_In();
	}
	
}

#include "Delay.h"
void EXTI0_IRQHandler(){
	// release the key
	if(EXTI_GetITStatus(EXTI_Line0)==SET){
		delay_ms(20);
		if(GPIOA->IDR & 0x01){
			StandBy_In();
		}
		EXTI_ClearITPendingBit(EXTI_Line0);
	}
}

